/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

use std::env;
use actix_web::HttpResponse;


pub async fn default_not_found_page() -> HttpResponse {
    HttpResponse::NotFound().body("Default Custom 404 Page")
}

const ENV_FILE_PATH: &str = "/etc/attestation_server/.env";

pub fn load_env()  {
    dotenv::from_filename(ENV_FILE_PATH).expect("Failed to load .env");
}

pub fn get_address() -> String {
    get_env_by_key("ATTESTATION_ADDRESS".to_string())
}

pub fn get_https_address() -> String {
    get_env_by_key("HTTPS_ADDRESS".to_string())
}

pub fn get_key_path() -> String {
    get_env_by_key("SERVER_KEY_PATH".to_string())
}

pub fn get_cert_path() -> String {
    get_env_by_key("SERVER_CERT_PATH".to_string())
}

pub fn get_env_by_key(key: String) -> String {
    let key_clone = key.clone();
    env::var(key).expect(&format!("{} must be set", key_clone))
}

pub fn get_env_value_or_default<T>(key: &str, default: T) -> T
where
    T: std::str::FromStr,
{
    env::var(key)
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(default)
}